package com.smarthome.api.mobile.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.druid.util.StringUtils;
import com.smarthome.common.exception.SmsException;
import com.smarthome.common.mobile.Service;
import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.account.AccountDoorService;
import com.smarthome.core.account.AccountService;
import com.smarthome.core.housemanager.BuildingManagerService;
import com.smarthome.core.housemanager.BuildingUnitManagerService;
import com.smarthome.core.housemanager.HouseDoorplatService;
import com.smarthome.core.message.util.MessageUtil;
import com.smarthome.domain.bean.ShAccount;
import com.smarthome.domain.bean.ShAccountDoor;
import com.smarthome.domain.bean.ShBuilding;
import com.smarthome.domain.bean.ShDoor;
import com.smarthome.domain.enums.AccountDoorStatus;
import com.smarthome.domain.enums.SmsTypeEnum;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileAccountInfoRequest;
import com.smarthome.domain.mobile.res.MobileAccountLoginResponse;

@org.springframework.stereotype.Service("mobile.account.info")
public class MobileAccountInfoService implements Service<MobileResponse<Map<String, String>>> {

    @Resource
    private AccountService accountService;

    @Resource
    private BuildingManagerService buildingManagerService;

    @Resource
    private BuildingUnitManagerService buildingUnitManagerService;

    @Resource
    private HouseDoorplatService houseDoorplatService;

    @Resource
    private AccountDoorService accountDoorService;

    /**
     * 更改密码
     * @param request
     * @param response
     */
    public void changePwd(MobileAccountInfoRequest request, MobileResponse<?> response) {
        MobileCodeEnum vali = valiOldPwd(request.getAccountId(), request.getOldPwd());
        if (!vali.getCode().equals("ok")) {
            response.setMobileCodeObj(vali);
            return;
        }
        ShAccount account = request.getAccount();
        if (account == null) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FOUND);
        } else {
            try {
                if (null == request.getLoginPwd()) {
                    response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
                } else {
                    account.setLoginPwd(SHACipher.encrypt(request.getLoginPwd()));
                    accountService.edit(account);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取用户个人信息
     * @param request
     * @param response
     */
    public void getAccount(MobileAccountInfoRequest request, MobileResponse<MobileAccountLoginResponse> response) {
        ShAccount account = request.getAccount();
        ShAccountDoor accountDoor = accountDoorService.getDefaultDoor(account.getId(), account.getResidenceId());

        MobileAccountLoginResponse logonRes = new MobileAccountLoginResponse();
        logonRes.setDoor(accountDoor);
        logonRes.setAccountId(account.getId());
        logonRes.setHeadImage(account.getHeadImage());
        logonRes.setMobile(account.getMobile());
        logonRes.setName(account.getName());
        logonRes.setSex(account.getSex());

        response.setData(logonRes);
    }

    /**
     * 根据小区获取楼栋信息
     * @param request
     * @param response
     */
    public void getBuildings(MobileAccountInfoRequest request, MobileResponse<List<ShBuilding>> response) {
        Long residengceId = request.getResidenceId();
        if (residengceId == null) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            List<ShBuilding> buildings = buildingManagerService.queryShBuildingsByResidenceId(residengceId);
            response.setData(buildings);
        }
    }

    /**
     * 根据楼栋获取单元列表
     * @param request
     * @param response
     */
    public void getBuildingUnits(MobileAccountInfoRequest request, MobileResponse<List<ShBuilding>> response) {
        Long buildingId = request.getBuildingId();
        if (buildingId == null) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            ShBuilding building = new ShBuilding();
            building.setParentId(buildingId);
            List<ShBuilding> buildingUnits = buildingUnitManagerService.queryBuildingByEntry(building);
            response.setData(buildingUnits);
        }

    }

    /**
     * 根据单元获取门牌号列表
     * @param request
     * @param response
     */
    public void getHouseDoors(MobileAccountInfoRequest request, MobileResponse<List<ShDoor>> response) {
        Long unitId = request.getUnitId();
        if (unitId == null) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            List<ShDoor> doors = houseDoorplatService.shShDoorsByBuildUnitId(unitId);
            response.setData(doors);
        }
    }

    /**
     * 完善用户信息(门牌号必须)
     * @param request
     * @param response
     */
    public void setHouse(MobileAccountInfoRequest request, MobileResponse<Map<String, Object>> response) {
        Long doorId = request.getDoorId();
        if (doorId == null) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            ShAccount account = request.getAccount();
            ShAccountDoor accountDoor = new ShAccountDoor();
            accountDoor.setAccountId(account.getId());
            accountDoor.setDoorId(doorId);
            if (accountDoorService.accountExist(accountDoor)) {
                response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_HOUSE_EXIST);
            } else if (request.getOwner() != null && request.getOwner() == 1 && accountDoorService.ownerExist(doorId)) {
                response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_HOUSE_OWNER_EXIST);
            } else {

                accountDoor.setResidenceId(request.getResidenceId());
                // 设置默认房屋
                accountDoorService.hasOtherHouse(accountDoor);
                accountDoor.setStatus(AccountDoorStatus.UNCHECK.getType());
                accountDoorService.add(accountDoor);
                ShDoor owner = houseDoorplatService.querydoorById(doorId);
                if (null != owner && !StringUtils.isEmpty(owner.getOwnerMobile())) {
                    try {
                        // 发送短信，生成记录
                        MessageUtil.sendTimelyForCaptchaUrid(SmsTypeEnum.ADD_DOOR_CODE,request.getResidenceId(), owner.getOwnerMobile(), accountDoor.getId() + "");
                        Map<String, Object> data = new HashMap<String, Object>();
                        data.put("doorDataId", accountDoor.getId());
                        response.setData(data);
                    } catch (SmsException e) {
                        e.getExceptionEnum().showMessage();
                        response.setMobileCodeObj(MobileCodeEnum.SMS_SEND_ERROR);
                    }
                }
            }
        }
    }

    /**
     * 重新获取业主验证码
     * @param request
     * @param response
     */
    public void resendOwnerCode(MobileAccountInfoRequest request, MobileResponse<Map<String, Object>> response) {
        Long doorDataId = request.getDoorDataId();
        ShAccountDoor accountDoor = accountDoorService.queryDataById(doorDataId);
        if(null == accountDoor){
        	response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FOUND);
        }else{
        	ShDoor owner = houseDoorplatService.querydoorById(accountDoor.getDoorId());
        	if (null != owner && !StringUtils.isEmpty(owner.getOwnerMobile())) {
        		try {
        			// 发送短信，生成记录
        			MessageUtil.sendTimelyForCaptchaUrid(SmsTypeEnum.ADD_DOOR_CODE,request.getResidenceId(), owner.getOwnerMobile(), accountDoor.getId() + "");
        		} catch (SmsException e) {
        			e.getExceptionEnum().showMessage();
        			response.setMobileCodeObj(MobileCodeEnum.SMS_SEND_ERROR);
        		}
        	}
        }
    }

    /**
     * 校验房东的验证码
     * @param request
     * @param response
     */
    public void valiHouseOwnerCode(MobileAccountInfoRequest request, MobileResponse<Map<String, String>> response) {
        String ckcode = request.getCkcode();
        Long doorDataId = request.getDoorDataId();
        try {
            boolean vali = MessageUtil.validateCaptcha(ckcode, doorDataId + "");
            if (vali) {
                ShAccountDoor accountDoor = accountDoorService.queryDataById(doorDataId);
                accountDoor.setStatus(AccountDoorStatus.OK.getType());// 房屋审核通过
                accountDoorService.add(accountDoor);
            } else {
                response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_CKCODE_ERR);
            }
        } catch (SmsException e) {
            response.setMobileCodeObj(e.getExceptionEnum().getCodeEnum());
        }

    }

    /**
     * 根据数据ID移除房屋
     * @param request
     * @param response
     */
    public void removeHouse(MobileAccountInfoRequest request, MobileResponse<Map<String, String>> response) {
        Long doorDataId = request.getDoorDataId();
        ShAccountDoor accountDoor = new ShAccountDoor();
        accountDoor.setId(doorDataId);
        accountDoorService.delete(accountDoor);
    }

    /**
     * 设置默认门牌
     * @param request
     * @param response
     */
    public void setDefaultDoor(MobileAccountInfoRequest request, MobileResponse<Map<String, String>> response) {
        Long residenceId = request.getResidenceId();
        Long doorDataId = request.getDoorDataId();
        ShAccountDoor accountDoor = accountDoorService.queryDataById(doorDataId);
        accountDoor.setResidenceId(residenceId);
        accountDoorService.changeOtherHouseNotDefault(accountDoor, doorDataId);
    }

    /**
     * 更改用户信息
     * @param request
     * @param response
     */
    public void changeAccountInfo(MobileAccountInfoRequest request, MobileResponse<Map<String, String>> response) {
        ShAccount account = request.getAccount();
        account.setName(request.getName());
        account.setSex(request.getSex());
        accountService.edit(account);
        accountService.resetAccountInCache(account.getId());
    }

    /**
     * 设置头像
     * @param request
     * @param response
     */
    public void setHeadImg(MobileAccountInfoRequest request, MobileResponse<Map<String, String>> response) {
        String headImage = request.getHeadImage();
        if (StringUtils.isEmpty(headImage)) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            ShAccount account = request.getAccount();
            account.setHeadImage(headImage);
            accountService.edit(account);
            accountService.resetAccountInCache(account.getId());
        }
    }

    private MobileCodeEnum valiOldPwd(Long accountId, String lastPwd) {
        MobileCodeEnum back = MobileCodeEnum.COMMON_SUCCESS;
        ShAccount account = accountService.queryAccountById(accountId);
        if (account == null) {
            back = MobileCodeEnum.ACCOUNT_NOT_FOUND;
        } else {
            try {
                if (null == lastPwd) {
                    back = MobileCodeEnum.ACCOUNT_NOT_FULL;
                } else if (null != lastPwd && !account.getLoginPwd().equals(SHACipher.encrypt(lastPwd))) {
                    back = MobileCodeEnum.ACCOUNT_OLDPWD_NOTCORRECT;
                }
            } catch (Exception e) {
                e.printStackTrace();
                back = MobileCodeEnum.SYSTEM_ERROR;
            }
        }
        return back;
    }
}
